/*******************************************************************************
 * Copyright (c) 2003 Object Knowledge Center B.V. (OKC), Object Knowledge
 * Center Group Ltd. (OKC-Group).
 *
 * This file is part of the Raw SOAP message sender plugin for Eclipse.

 * The Raw SOAP message sender plugin for Eclipse is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation;
 * either version 2 of the License, or (at your option) any later version.
 * 
 * The Raw SOAP message sender plugin for Eclipse is distributed
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with the Raw SOAP message sender plugin for Eclipse;
 * if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *  
 *******************************************************************************/

package villa.tools.mq;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Display;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.ibm.mq.*;
import com.ibm.mq.constants.CMQC;


public class RawMessageSender extends Thread {

	private class ShowResponseThread implements Runnable {
		
		private StyledText responseField = null;
		private String response = null;
		
		public ShowResponseThread(StyledText aResponseField, String aResponse) {
			responseField = aResponseField;
			response = aResponse;
		}
		
		public void run() {
						responseField.setText(response);
		}
	}

	private String hostName = null;
	private String message = null;
	private String cola = null;
	private String channel = null;
	private Integer port = null;
	private StyledText styledText = null;
	
	public RawMessageSender(String aHostName, Integer aPort, String aChannel, String aQueue, String aMessage, StyledText aStyledText) {
		
		
		hostName = aHostName;
		port = aPort;
		channel = aChannel;
		cola = aQueue;
		message = aMessage;
		styledText = aStyledText;
		
		
	}

	/**
	 * @param urlString The URL (protocol, host, port and directory) to connect to.
	 * @param message The SOAP message that is to be sent to the web service
	 * @return The result message of the server
	 */
	public void run() {
		
		Runnable showResponseThread =
			new ShowResponseThread(styledText, styledText.getText());
		Display.getDefault().asyncExec(showResponseThread);
		
		styledText.setText(styledText.getText()+ "::fin");
	
		
	}
	
	public static String prettyPrint(String unformattedString) {
		try {
			String oneLine = trimXML(unformattedString);
			InputSource inputSource = new InputSource(new StringReader(oneLine));
			StringWriter writer = new StringWriter();
			
			DocumentBuilder builder =
				DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document document = builder.parse(inputSource);
			
                       DOMSource domSource = new DOMSource(document);
                       StreamResult streamResult = new StreamResult(writer);
                       TransformerFactory tf = TransformerFactory.newInstance();
                       Transformer serializer = tf.newTransformer();
                       serializer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
                       // serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
                       serializer.setOutputProperty(OutputKeys.INDENT,"yes");
                       serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
                       serializer.transform(domSource, streamResult); 

			return writer.getBuffer().toString();
		} catch (ParserConfigurationException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
			return unformattedString;
		} catch (SAXException e) {
			// Malformed XML, this only fills up the log, whereas user did not
			// provide well formed XML, so ignore
			return unformattedString;
		} catch (FactoryConfigurationError e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
			return unformattedString;
		} catch (IOException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
			return unformattedString;
		} catch (TransformerConfigurationException e) {
                        System.err.println(e.getMessage());
                        e.printStackTrace();
                        return unformattedString;
                } catch (TransformerException e) {
                        System.err.println(e.getMessage());
                        e.printStackTrace();
                        return unformattedString;
                }
	}

	/**
	 * remove blanks, tabs and linebreaks between the tags
	 * @param xml
	 * @return
	 */
	private static String trimXML(String xml) {
		
		int len = xml.length();
		StringBuffer result = new StringBuffer(len);
		int pos = 0;
		while (pos < len) {
			// skip spaces forward
			while ((pos < len) && (isSpace(xml.charAt(pos))))
					pos += 1;
			if (pos >= len)
				break;
			int startCopy = pos;
			// search "<"
			while ((pos < len) && (xml.charAt(pos) != '<'))
				pos += 1;
			int nextLess = pos;
			pos -= 1;
			// skip spaces backward
			while ((pos >= startCopy) && (isSpace(xml.charAt(pos))))
				pos -= 1;
			int endCopy = pos;
			// do copy
			if (endCopy >= startCopy)
				result.append(xml.substring(startCopy, endCopy + 1));
			
			if (nextLess >= len)
				break;

			pos = nextLess;
			// search ">"
			while ((pos < len) && (xml.charAt(pos) != '>'))
				pos += 1;
			int nextGreater = pos;
			// do copy
			if (nextGreater >= nextLess)
				result.append(xml.substring(nextLess, nextGreater + 1));
			
			pos = nextGreater + 1;
		}
		return result.toString();
	}

	private static boolean isSpace(char c) {
		return (" \t\r\n".indexOf(c) != -1);
	}
	
	
}
